﻿/*
This file is part of Claymore.
Copyright (C) 2009, Fabrice Michellonet (fabrice dot michellonet at gmail dot com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace Claymore
{
    public class ClaymoreViewManager : IViewManager
    {
        #region Fields

        protected IDictionary<string, Type> _viewTypeName2ViewType;
        protected IDictionary<Type, IView> _viewType2View;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="ClaymoreViewManager"/> class.
        /// </summary>
        public ClaymoreViewManager()
        {
            _viewTypeName2ViewType = new Dictionary<string, Type>();
            _viewType2View = new Dictionary<Type, IView>();
        }

        /// <summary>
        /// Adds the views assembly.
        /// </summary>
        /// <param name="asm">The asm.</param>
        public virtual void AddViewsAssembly(Assembly asm)
        {
            foreach (Type type in asm.GetTypes())
            {
                if (typeof(IView).IsAssignableFrom(type))
                {
                    AddViewTypeName(type);
                }
            }
        }

        /// <summary>
        /// Adds the view type name in the views dictionnary.
        /// </summary>
        /// <param name="viewType">The view type.</param>
        protected virtual void AddViewTypeName(Type viewType)
        {
            if (!_viewTypeName2ViewType.ContainsKey(viewType.Name))
                _viewTypeName2ViewType.Add(viewType.Name, viewType);
        }

        /// <summary>
        /// Adds the view to the instanciated views dictionnary.
        /// </summary>
        /// <param name="view">The view.</param>
        protected virtual void AddView(IView view)
        {
            Type viewType = view.GetType();

            if (!_viewType2View.ContainsKey(viewType))
                _viewType2View.Add(viewType, view);
        }

        /// <summary>
        /// Gets a view based on it's name.
        /// </summary>
        /// <param name="viewName">Name of the view.</param>
        /// <returns></returns>
        public virtual IView GetView(string viewName)
        {
            IView view = null;

            if (_viewTypeName2ViewType.ContainsKey(viewName))
            {
                Type viewType = _viewTypeName2ViewType[viewName];

                if (_viewType2View.ContainsKey(viewType))
                    view = _viewType2View[viewType];
            }
            return view;
        }

        /// <summary>
        /// Creates the view based on it's name
        /// </summary>
        /// <param name="viewName">Name of the view.</param>
        /// <returns></returns>
        public virtual IView CreateView(string viewName)
        {
            IView view = null;

            if (_viewTypeName2ViewType.ContainsKey(viewName))
            {
                Type viewType = _viewTypeName2ViewType[viewName];

                try
                {
                    view = (IView)Activator.CreateInstance(viewType);

                    StepIntoView(view);

                    // if it's the first instance of the view then we store it.
                    //if(!_viewType2View.ContainsKey(viewType))
                    //    _viewType2View.Add(viewType, view);
                    AddView(view);

                    return view;
                }
                catch (Exception)
                {
                    throw new InvalidOperationException("IView implementation must have a parameterless constructor.");
                }
            }
            return view;
        }

        /// <summary>
        /// Steps the into view to find child views.
        /// </summary>
        /// <param name="view">The view.</param>
        protected virtual void StepIntoView(IView view)
        {
            Control container = view as Control;
            if (container != null)
            {
                StepIntoControl(container);
            }
        }

        /// <summary>
        /// Steps the into control.
        /// </summary>
        /// <param name="ctrl">The CTRL.</param>
        protected virtual void StepIntoControl(Control ctrl)
        {
            foreach (Control c in ctrl.Controls)
            {
                StepIntoControl(c);
                IView childView = c as IView;
                if (childView != null)
                {
                    AddViewTypeName(childView.GetType());
                    AddView(childView);
                }
            }
        }

        /// <summary>
        /// Gets a view based on it's implemented interface.
        /// </summary>
        /// <typeparam name="TIView">The type of the I view.</typeparam>
        /// <returns></returns>
        public virtual TIView GetView<TIView>()
            where TIView : IView
        {
            TIView view = default(TIView);

            Type viewType = _viewTypeName2ViewType.Values.FirstOrDefault(tp => typeof(TIView).IsAssignableFrom(tp));

            if (_viewType2View.ContainsKey(viewType))
                view = (TIView)_viewType2View[viewType];

            return view;
        }

        /// <summary>
        /// Creates a view based on it's implemented interface.
        /// </summary>
        /// <typeparam name="TIView">The type of the I view.</typeparam>
        /// <returns></returns>
        public virtual TIView CreateView<TIView>()
            where TIView : IView
        {

            TIView view = default(TIView);

            Type viewType = _viewTypeName2ViewType.Values.FirstOrDefault(tp => typeof(TIView).IsAssignableFrom(tp));
            if (viewType == null)
                return view;

            view = (TIView)Activator.CreateInstance(viewType);

            StepIntoView(view);

            // if it's the first instance of the view then we store it.
            AddView(view);

            return view;
        }
    }
}
